<?php
namespace Admin\Controller;

use Think\Controller;

class TotaleController extends Controller
{
    public function index()
    {
        $now = I('start', date('Y-m-d', strtotime('-1 day')));
//        $now = '2017-12-11';
        $where = "created_at >= '". $now . ' 00:00:00' ."' and created_at <= '".$now . ' 23:59:59'."'";
        $data = M('order')->where($where)->order('created_at desc')->fetchSql(false)->select();

        $sum = M('order')->where($where)->sum('order_total');
        $order_pay = M('order')->where($where)->field('order_pay, count(*) as count')->group('order_pay')->select();
        foreach ($order_pay as &$val) {
            $val['order_pay'] = $val['order_pay'] == '免单' ? '签单' : $val['order_pay'];
        }


        //统计桌子使用率
        $table_id = array_column($data, 'order_name');
        $table = M('table')->where(array('t_id' => array('in', implode(',', $table_id))))->fetchSql(false)->select();
        $baifen = array_count_values($table_id);
        foreach ($baifen as $k => $v) {
            //$baifen$cpl[$k] = round($v / array_sum($baifen) * 100, 2);
            $cpl[$k] = $v;
        }
        //合并桌子
        foreach ($table as $k => &$v) {
            $v['cpl'] = isset($cpl[$v['t_id']]) ? $cpl[$v['t_id']] : '';
        }
        usort($table, function ($a, $b) {
            return $a['cpl'] > $b['cpl'] ? -1 : 1;
        });
        $this->assign('table', $table);
        $this->assign('order_pay', $order_pay);
        $this->assign('order_total', number_format($sum, 2));
        $this->assign('start', $now);
        $this->assign('data', $data);
        $this->display();
    }
}